import 'dart:typed_data';

import 'package:bson/bson.dart';

/// 与[Map]的区别是，里面的二进制会以[BsonBinary]储存
typedef Bson = Map;

/// dart转化为二进制
extension Encode on Object {
  // 中间状态（保持[BsonBinary]，否则会变成普通的[List]）
  BsonBinary get encode => BSON().serialize(this);
}

Bson toBson(dynamic input) {
  if (input is BsonBinary) {
    return BSON().deserialize(input);
  } else if (input is Uint8List) {
    return BSON().deserialize(BsonBinary.from(input));
  } else {
    throw Exception("未知的类型");
  }
}

Uint8List toBytes(dynamic input) {
  if (input is BsonBinary) {
    return input.byteList;
  } else if (input is Object) {
    return input.encode.byteList;
  } else {
    throw Exception("未知的类型");
  }
}
